<?php

namespace App\Models;

use App\Admin\Controllers\TeamController;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Tests\Models\User;
use App\Models\TeamBook;

class ActivityTeamModel extends Model
{
    //读书小组
    protected $table='activity_team';

    /**
     * 表明模型是否应该被打上时间戳
     *
     * @var bool
     */
    public $timestamps = true;

    protected $fillable = [
        'id',
        'team_name',
        'max_number',
        'team_number',
        'company_id',
        'user_id',
        'key_id',
        'team_stash',
        'team_type',
        'team_logo',
        'team_synopsis',
        'team_phone',
        'team_contacts',
        'wee_holiday',
        'day_holiday_start',
        'day_holiday_end',
        'created_at'
    ];

    public function setWeeHolidayAttribute($value){

        return $this->attributes['wee_holiday'] =  implode(',',$value);
    }

    public function getWeeHolidayAttribute($value){
        if(empty($value)){
            return [];
        }
        return explode(',',$value);
    }

    public function user(){
        return  $this->belongsTo(UserModel::class,'user_id','id');
    }

    public function many_team_book()
    {
        return $this->hasMany(TeamBook::class, 'team_id','id');
    }

    public function team_book(){
        //return $this->belongsTo(TeamBookActivity::class,'','');
        return $this->belongsToMany(BookModel::class, 'team_book',
            'team_id', 'book_id');
    }

    public function getTeamLogoAttribute($value){
        return oss_domain().'/'.$value;
    }

    public function team_user(){
        return $this->hasMany(ActivityTeamUser::class,'team_id','id');
    }

    public function team_user_info(){
        return $this->belongsToMany(UserModel::class,'activity_team_user','team_id','user_id');
    }

    public function create_activity_team($request){
        DB::beginTransaction(); //开启事务
        try{

            $team_model = $this->create($request);
            //插入一条小组成员
            //team_id class_id user_id team_user_stash
            $data = [];
            $data['team_id'] = $team_model->id;
            $data['key_id'] = $request['key_id'];
            $data['user_id'] = $request['user_id'];
            $data['team_user_stash'] = 1;//创建者不用审核
            $data['team_type'] = $request['team_type'];
            $data['is_admin'] =1;

            ActivityTeamUser::create($data);
            DB::commit();
            return true;
        }catch (\Exception $e){
            DB::rollBack();
            Log::info('创建小组失败'.$e -> getMessage());
            return false;
        }

    }

    public function team_list($class_id,$team_type=[],$company_id,$key_work){
        $q = $this->where('key_id',$class_id);
        if(!empty($class_id)){
            $q->where('key_id',$class_id)->whereIn('team_type',$team_type);
        }

        if(!empty($team_type)){
            $q->whereIn('team_type',$team_type);
        }

        if(!empty($key_work)){
            $q->orWhere('team_name','like','%'.$key_work.'%');
        }

        if($team_type[0] == 1){
            //dd($company_id);
            $q->where('company_id',$company_id);
        }

        return
            $q
            ->select(['id','team_name'])
            ->orderBy('id','desc')
            ->get()->toArray();
    }

    public function other_team_list($class_id,$team_type,$user_id){
        //获取小组ID
        $team_ids = ActivityTeamUser::whereIn('team_type',$team_type)->where('user_id','!=',$user_id)
            ->pluck('team_id')
            ->toArray();
        if(!empty($class_id)){
            $q = $this->where('key_id',$class_id)->whereIn('team_type',$team_type);
        }else{
            $q = $this->whereIn('team_type',$team_type);
        }
        return
            $q
                ->select([
                    'id',
                    'team_name',
                    'team_logo',
                    'team_synopsis',
                    'team_integral',
                    'team_type',
                    'user_id',
                    'wee_holiday',
                    'day_holiday_start',
                    'day_holiday_end',
                    'created_at',
                    ])
                ->whereIn('id',$team_ids)
                ->orderBy('id','desc')
                ->get()
                ->toArray();
    }

    public function team_info($team_id,$team_type,$user_id){

            $q = $this->whereIn('team_type',$team_type)
                ->select([
                    'id',
                    'team_name',
                    'team_logo',
                    'key_id',
                    'team_synopsis',
                    'team_type',
                    'user_id',
                    'wee_holiday',
                    'day_holiday_start',
                    'day_holiday_end',
                    'created_at',
                ])
                ->where('id',$team_id)
                ->with([
                    'team_user'=>function($q){
                        $q->select([
                           'user_id',
                           'team_id',
                           'company_name',
                           'team_user_stash',
                           'phone',
                           'created_at',
                        ])->with([
                            'user'=>function($q){
                                $q->select([
                                    'id',
                                    'nickname',
                                    'avatar',
                                    'total_integral',
                                    'user_integral',
                                ]);
                            },
                        ]);
                    },
                ])
                ->orderBy('id','desc')
                //->where('team_user_stash',1)
                ->first();
                if($user_id == $q->user_id){
                    $q->is_admin = 1;
                }else{
                    $q->is_admin = 2;
                }

                //dd($q->key_id);
                    $q->class_arrange = ClassWorkModel::where('key_id',$q->key_id)
                        ->whereIn('class_type',$team_type)
                        ->select([
                            'id',
                            'article_id',
                        ])
                        ->with([
                            'article'=>function($q){
                                $q->select([
                                   'id',
                                   'article_title',
                                ]);
                            },
                        ])
                        ->get()->toArray();

                return $q;
    }


    public function my_create_team($user_id,$team_type){
            if(!empty($team_type)){
                $q = $this->where('user_id',$user_id)->where('team_type',$team_type);
            }else{
                $q = $this->where('user_id',$user_id);
            }
            return $q
            ->select([
                'id',
                'team_name',
                'max_number',
                'team_number',
                'company_id',
                'key_id',
                'team_stash',
                'team_type',
                'team_logo',
                'team_synopsis',
                'team_phone',
                'team_contacts',
                'wee_holiday',
                'day_holiday_start',
                'day_holiday_end',
                'created_at',
            ])
            ->with([
                'team_user_info'=>function($q){
                    $q->select([
                        'user.id',
                        'user.nickname',
                        'user.avatar',
                        'activity_team_user.team_id',
                        'activity_team_user.name',
                        'activity_team_user.phone',
                        'activity_team_user.company_name',
                        'activity_team_user.user_id',
                        'activity_team_user.team_user_stash',
                        'activity_team_user.created_at',
                    ]);
                },
            ])
            ->orderBy('created_at','desc')
            ->paginate(15);
    }

    public function integral_rank($user_id,$type){

        //获取所有小组
        $team_ids = ActivityTeamUser::where('user_id',$user_id)
            ->pluck('team_id')
            ->toArray();
        //获取小组排名
        $team_order = ActivityTeamModel::whereIn('id',$team_ids)
            ->whereIn('team_type',$type)
            ->orderBy('team_integral','desc')
            ->pluck('id')
            ->toArray();

        $team_user = ActivityTeamUser::whereIn('team_id',$team_ids)
            ->whereIn('team_type',$type)
            //->where('team_user_stash',1)
            ->select([
                'user_id',
                'team_id',
                //'team_user_stash',
                'team_type',
            ])
            ->with([
              'user'=>function($q){
                    $q->select([
                       'id',
                       'nickname',
                       'avatar',
                    ]);
              },
                'team'=>function($q){
                    $q->select([
                        'id',
                        'team_name',
                        'team_logo',
                        'team_integral',
                    ]);
                }
            ])
            //->groupBY('team_id')
            ->get()
            ->groupBY('team_id')
            ->toArray();
          //dd(array_merge($team_user));
        $team_user = array_merge($team_user);
        if(count($team_user)>0){
            foreach ($team_user as $k=>$v){

                foreach ($v as $kk=>$vv){
                    //对应的小组的排名
                    $key = array_search($vv['team_id'], $team_order);
                    $team_user[$k][$kk]['team_order'] = $key + 1;
                    $total_integral = \DB::table('sign_team')
                        ->where('user_id',$vv['user_id'])
                        ->where('team_id',$vv['team_id'])
                        ->select([
                        \DB::raw("sum(integral) as total_integral"),
                    ])
                        ->whereIn('team_type',$type)
                        ->first();
                    $team_user[$k][$kk]['total_integral'] = empty($total_integral->total_integral)?0:$total_integral->total_integral;
                }
            }
        }

        //根据总分排序
        foreach ($team_user as $k => $v) {
            $fieldArr = array();
            foreach ($v as $kk=>$vv) {

                $fieldArr[$kk] = $vv['total_integral'];
            }
            array_multisort($fieldArr, SORT_DESC, $team_user[$k]);
        }
        return $team_user;
    }

    public function team_integral_rank($user_id,$type){

        $q = $this->whereIn('team_type',$type);
        if(!empty($user_id)){
            $team_ids = ActivityTeamUser::where('user_id',$user_id)
                ->where('team_user_stash',1)
                ->pluck('team_id')
                ->toArray();
            $q->whereIn('id',$team_ids);
        }
        return
            $q
            ->orderBy('team_integral','desc')
            ->get();
    }
}
